import Tkinter
from Tkinter import *
from addUser import addUser
from delUser import delUser
import redditConfig
import pickle
from client import main
import subprocess

class RedditNotifier(Tkinter.Tk):
    def __init__(self,parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.grid()

        run = Tkinter.Button(self,text=u"Run Now",command=self.RunNow)
        run.grid(column=0,row=0,columnspan=2,sticky='EW',padx=5,pady=5)

        add = Tkinter.Button(self,text=u"Add User",command=self.OnAddUser)
        add.grid(column=0,row=1,sticky='EW',padx=5,pady=5)

        delete = Tkinter.Button(self,text=u"Delete User",command=self.OnDelUser)
        delete.grid(column=1,row=1,sticky='EW',padx=5,pady=5)

        self.grid_columnconfigure(0,weight=1)
        self.resizable(False,False)
        self.update()
        self.geometry('200x100')
        

    def OnAddUser(self):
        print 'will add'
        self.top = win = Toplevel()
        
        win.entryVariable = Tkinter.StringVar()
        win.entry = Tkinter.Entry(win,textvariable=win.entryVariable)
        win.entry.grid(column=0,row=0,sticky='EW')  

        win.save = Tkinter.Button(win,text=u"Save User",command=self.OnSaveUser)
        win.save.grid(column=0,row=1,sticky='EW')

    def OnSaveUser(self):
        print 'saving', self.top.entryVariable.get()
        addUser(self.top.entryVariable.get())
        self.top.destroy()

    def OnDelUser(self):
        print 'will delete'
        self.top = win = Toplevel()
        
        #win.entryVariable = Tkinter.StringVar()
        #win.entry = Tkinter.Entry(win,textvariable=win.entryVariable)
        #win.entry.grid(column=0,row=0,sticky='EW')

        win.s = Tkinter.Scrollbar(win)
        win.L = Tkinter.Listbox(win)

        win.s['command']=win.L.yview
        win.L['yscrollcommand']=win.s.set

        userList = pickle.load(open(redditConfig.pickleFile,'rb'))
        for user in userList:
            win.L.insert(Tkinter.END,user)

        win.L.grid(column=0,row=0,sticky='EW')
        win.s.grid(column=1,row=0,sticky='NS')

        win.save = Tkinter.Button(win,text=u"Delete User",command=self.OnDoDelUser)
        win.save.grid(column=0,row=1,columnspan=2,sticky='EW')

    def OnDoDelUser(self):
        user = self.top.L.get(self.top.L.curselection())
        print 'deleting', user
        delUser(user)
        self.top.destroy()

    def RunNow(self):
        print 'run now'
        subprocess.Popen(["python.exe",redditConfig.clientLocation])

if __name__ == "__main__":
    app = RedditNotifier(None)
    app.title('Reddit Notifier')
    app.mainloop()
